<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8"/>
    <title>聊天室</title>
    <link href="../assets/bootstrap.min.css" rel="stylesheet">
    <style>
        .myImg {
            height: 64px;
            width: 64px;
        }

        body {
            background-image: url("../picture/background.jpg");
        }
    </style>
</head>

<body class="bg-light">
<div class="container p-2">
    <div class="card">
        <div class="card-header bg-success text-light">
            <a class="text-light" href="javascript:history.back()">←返回</a>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="panel-container col-sm-12 col-md-2 border-end border-5">
                    &nbsp;<b>当前用户</b>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item" id="nowClientName">当前用户</li>
                    </ul>
                    &nbsp;<b>其它用户</b>
                    <ul class="list-group list-group-flush" id="otherClient" style="cursor: pointer;">
                    </ul>
                </div>
                <!-- 消息显示 -->
                <div class="col-sm-12 col-md-8" style="height: 450px; overflow-y: auto;" id="showMsg">
                    <div class="container" id="msgContainer">
                    </div>
                </div>
                <!-- 发送框-->
                <div class="card-footer">
                    <form class="input-group" onsubmit="return false">
                        <label class="mx-3" for="myFile">
                            <img alt="img" src="../assets/icon/img.svg">
                        </label>
                        <input type="file" id="myFile" accept="image/*" hidden="hidden"/>
                        <label for="waitSend"></label><input type="text" class="form-control" placeholder="输入消息"
                                                             id="waitSend"/>
                        <button class="btn btn-success" type="submit" onclick="sendMsg()">
                            <img alt="send" src="../assets/icon/send.svg">发送
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script src="../assets/bootstrap.bundle.min.js"></script>
<script src="../assets/axios.js"></script>
<script src="../js/z-alert.js"></script>
<script src="../js/z-chatDate.js"></script>
<script src="../js/request.js"></script>
<script>
    const msgContainer = document.getElementById("msgContainer");
    let clientId;
    "use strict";
    const ws = new WebSocket("ws://localhost:8083/chat");  // 建立WebSocket对象
    window.onload = () => {
        const href = window.location.href
        if (href.indexOf("?") !== -1) {
            const getId = href.split("?")[1]
            if (!isNaN(parseInt(getId))) {
                cutClient(getId, false)
            }
        } else axios("msg/d").then(resp => {
            clientId = resp.data
            requestMsgList()
            readGroup()
        })
    }// 读取消息列表
    function requestMsgList() {
        console.log("刷新了页面")
        axios("msg/aClient?clientId=" + clientId).then(resp => {
            const msgList = resp.data
            msgContainer.innerHTML = ""
            for (let i = 0; i < msgList.length; i++) parseOneLine(msgList[i]);
            const showMsg = document.getElementById("showMsg");
            setTimeout(()=>{
                showMsg.scrollTop = showMsg.scrollHeight
            },300)
        })
    }// 读取用户联系过的用户
    function readGroup(isOld = true) {
        axios("msg/d/group?clientId=" + clientId).then(resp => {
            const groupList = resp.data,
                otherClient = document.getElementById("otherClient"),
                zero = groupList[0]
            otherClient.innerHTML = ''
            if (isOld) document.getElementById("nowClientName").innerText = zero["clientName"]
            else otherClient.innerHTML += `<li class="list-group-item" onclick="cutClient(${zero["clientId"]})">${zero["clientName"]}</li>`
            for (let i = 1; i < groupList.length; i++) {
                const one = groupList[i]
                otherClient.innerHTML += `<li class="list-group-item" onclick="cutClient(${one["clientId"]})">${one["clientName"]}</li>`
            }
        })
    }//接受消息
    ws.onmessage = function (ev) {
        const dataStr = ev.data;
        console.log("从客户处接收的消息:"+dataStr)
        requestMsgList() // 这里是接受到消息之后刷新
    }// 关闭链接
    ws.onclose= function () {
        showAlert("你已离线")
    }// 读取并处理一行消息
    function parseOneLine(ele) {
        const {clientName, doctorName, isClient, msgContent, createTime, clientPhoto, doctorPhoto, isImg} = ele;
        if (isClient) writeClient(clientName, msgContent, createTime, clientPhoto, isImg)
        else writeDoctor(doctorName, msgContent, createTime, doctorPhoto, isImg)
    }// 写入用户消息
    function writeClient(clientName, msgContent, createTime, photo, isImg) {
        if (isImg) msgContent = `<img src="${BACK_URL}common/downChat?name=${msgContent}" class="w-100" alt="" />`
        msgContainer.innerHTML += `<div class="d-flex justify-content-start my-3">
                                <img src="${BACK_URL}common/download?name=${photo}" class="rounded-circle myImg" alt="" />
                                <div class="card w-50">
                                    <div class="card-body">
                                        <div class="card-title">
                                            <small>${clientName} ${getDate(createTime)}</small>
                                        </div>
                                        <div class="card-text">
                                            ${msgContent}
                                        </div></div></div></div>`
    }// 写入医生消息
    function writeDoctor(doctorName, msgContent, createTime, photo, isImg) {
        if (isImg) msgContent = `<img src="${BACK_URL}common/downChat?name=${msgContent}" class="w-100" alt="" />`
        msgContainer.innerHTML += `<div class="d-flex justify-content-end my-3">
                                <div class="card bg-success bg-gradient text-light w-50">
                                    <div class="card-body">
                                        <div class="card-title">
                                            <small>${doctorName} ${getDate(createTime)}</small>
                                        </div>
                                        <div class="card-text">
                                            ${msgContent}
                                        </div></div></div>
                                <img src="${BACK_URL}common/download?name=${photo}" class="rounded-circle myImg" alt="" />
                            </div>`
    }// 点击其它的用户
    function cutClient(getID, isOld = true) {
        clientId = getID
        axios("client/one?clientId=" + getID).then(resp => {
            document.getElementById("nowClientName").innerText = resp.data["clientName"]
        })
        requestMsgList()
        readGroup(isOld)
    }// 点击发送按钮
    function sendMsg() {
        const waitSend = document.getElementById("waitSend");
        const content = waitSend.value;
        waitSend.value = "";
        if (content === "") return;
        const json = {"msgContent": content, "clientId": clientId, "isClient": false}
        //保存数据
        axios.post("msg/d", {"msgContent": content, "clientId": clientId}).then(resp => {
            if (resp.data["code"] === 1) requestMsgList();
            else showAlert("发送失败");
        })
        //发送数据
        ws.send(JSON.stringify(json));
    }// 发送图片
    document.getElementById("myFile").onchange = () => {
        const myFile = this.myFile.files[0]
        if (myFile.size > 3145700) showAlert("上传的图片应小于3MB")
        else {
            const formData = new FormData();
            formData.append("myFile", myFile)
            axios.post("common/upChat", formData).then(resp => {
                const json = {"msgContent": resp.data, "clientId": clientId, "isClient": false, "isImg": true}
                //保存数据
                axios.post("msg/d", json).then(resp => {
                    if (resp.data["code"] === 1) requestMsgList();
                    else showAlert("发送失败");
                })
                //发送数据
                ws.send(JSON.stringify(json));
            })
        }
    }
</script>

</html>